﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Reflection;

namespace WarOfDev.AutoTasks
{
    public class ExecuteManager
    {
        private List<TaskEntity> taskList;

        public ExecuteManager() {

            taskList= ConfigurationManager.GetSection("WarOfDevServicrsConfig") as List<TaskEntity>;

            foreach (var task in taskList)
            {
                var typeName = task.ExecutorType;
                var arr = typeName.Split(',');

                if (arr.Length == 2)
                {
                    var assembleName = arr[1];
                    var type = arr[0];

                    Assembly assembly = Assembly.Load(assembleName);
                    task.Executor= assembly.CreateInstance(type) as IExecutable;
                }
            }
        }

        public void BindTimer()
        {
            foreach (TaskEntity task in taskList)
            {
                if (task.Executor == null) continue;

                System.Timers.Timer timer = new System.Timers.Timer
                {
                    AutoReset=false,
                    Enabled=true,
                    Interval=task.Interval
                };

                timer.Elapsed+=new System.Timers.ElapsedEventHandler(task.timer_Elapsed);
            }
        }
    }
}
